import { IWorkSpaceData } from '@/appUtils/appData/interfaces'
import { getWorkSpaceDataDirById } from '@/appUtils/appData/paths'
import { openWorkSpace, saveWorkSpaceData } from '@/appUtils/appData/workSpace'
import { debounce, set } from 'lodash-es'
import { defineStore } from 'pinia'
import { ref, toRaw } from 'vue'
import { useDesignStore } from './design'

// const workSpaceHistoryData = readWorkSpaceHistory()

let workSpaceData: IWorkSpaceData | null = null

export const getCurrentWorkSpaceData = () => workSpaceData

export const useWorkSpaceStore = defineStore('workSpace', () => {
    const data = ref<IWorkSpaceData | null>(null)

    // 获取工作空间数据目录
    const getWorkSpaceDataDir = async () => {
        if (!data.value) {
            return
        }
        const dir = await getWorkSpaceDataDirById(data.value.id)
        return dir
    }

    // 打开一个工作空间
    const open = async (dir: string) => {
        const resData = await openWorkSpace(dir)
        data.value = resData
        workSpaceData = resData
        // 初始化设计稿数据
        useDesignStore().init()
    }

    // 保存数据
    const save = debounce(saveWorkSpaceData, 100)

    // 更新数据
    const update = (prop: string, value: any) => {
        if (!data.value) {
            return
        }
        set(data.value, prop, value)
        setTimeout(() => {
            if (!data.value) {
                return
            }
            save({
                id: data.value.id,
                data: toRaw(data.value)
            })
        }, 500)
    }

    return {
        data,
        open,
        getWorkSpaceDataDir,
        update
    }
})
